package com.idealighter.game.roomcard.struct;

import com.idealighter.game.core.annotation.RoomCfg;
import com.idealighter.game.core.common.Game;
import com.idealighter.game.core.common.GameMap;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.ibatis.io.ResolverUtil;
import org.apache.ibatis.io.ResolverUtil.AnnotatedWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RoomCardRoomListMap {
  private static final Logger LOG = LoggerFactory.getLogger(RoomCardGameCfgMap.class);
  private static final String CFG_PATH = "com.idealighter.game.roomcard.struct.roomcfg";
  private static Map<Integer, Class<? extends RoomCardRoomCfg<? extends RoomCardRoomCfgValue>>> map;

  static {
    map = new HashMap<Integer, Class<? extends RoomCardRoomCfg<? extends RoomCardRoomCfgValue>>>();

    ResolverUtil<RoomCardRoomCfg<? extends RoomCardRoomCfgValue>> resolver =
        new ResolverUtil<RoomCardRoomCfg<? extends RoomCardRoomCfgValue>>().find((type) -> {
          // 首先判断type为RoomCardGameCfg的子类
          if (RoomCardRoomCfg.class.isAssignableFrom(type)) {
            // 再判断注解
            return new AnnotatedWith(RoomCfg.class).matches(type);
          } else {
            return false;
          }
        }, CFG_PATH);

    Set<Class<? extends RoomCardRoomCfg<? extends RoomCardRoomCfgValue>>> classes =
        resolver.getClasses();
    if (classes != null && !classes.isEmpty()) {
      for (Class<? extends RoomCardRoomCfg<? extends RoomCardRoomCfgValue>> clz : classes) {
        RoomCfg ctl = clz.getAnnotation(RoomCfg.class);
        int gameId = ctl.value();
        Game game = GameMap.getGameByGameId(gameId);
        if (game == null) {
          LOG.warn("游戏[{}]cfg配置有误", gameId);
          System.exit(1);
        }
        if (map.containsKey(gameId)) {
          LOG.warn("游戏[{}]cfg重复", gameId);
          System.exit(1);
        }
        map.put(gameId, clz);
      }
    }
  }

  public static Class<? extends RoomCardRoomCfg<? extends RoomCardRoomCfgValue>> findRoomCfgByGame(
      int gameId) {
    return map.get(gameId);
  }
}
